//
//  LeftViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "LeftViewController.h"
#import "PersonalDataViewController.h"
#import "XHDrawerController.h"
#import "LeftDrawerTableViewCell.h"
#import "BaseNavigation.h"
#import "UserDetailModel.h"
#import "AnHaoViewController.h"
#import "MyHealthLogViewController.h"
#import "MyFamilyViewController.h"
#import "SystemSetViewController.h"
#import "EditSignatureViewController.h"
#import "MyDoctorViewController.h"
#import "ShareViewController.h"
#import "TaskViewController.h"
#import "UserId.h"
#import "MyFocusViewcontroller.h"
#import "MyFriendViewController.h"
@interface LeftViewController ()<UITableViewDataSource,UITableViewDelegate>
/**
 *  头像，名字等相关信息上面覆盖的一层透明的view(为了添加手势实现跳转页面)
 */
@property (strong, nonatomic) IBOutlet UIView *firstSurfaceView;
/**
 *  签名视图上面添加的一层透明的view
 */
@property (strong, nonatomic) IBOutlet UIView *secondSurfaceView;
/**
 *  头像
 */
@property (strong, nonatomic) IBOutlet UIImageView *leftDrawerHeaderImageView;
/**
 *  头像遮板
 */
@property (strong, nonatomic) IBOutlet UIImageView *imageViewBaffle;

/**
 *  名字
 */
@property (strong, nonatomic) IBOutlet UILabel *leftDrawerNameLabel;


/**
 *  话题label
 */
@property (strong, nonatomic) IBOutlet UILabel *topLabel;
/**
 *  话题信息(数据)
 */
@property (strong, nonatomic) IBOutlet UILabel *leftDrawerTopicContentLabel;

/**
 *  竖线
 */
@property (strong, nonatomic) IBOutlet UIView *verticalLine;
/**
 *  积分
 */
@property (strong, nonatomic) IBOutlet UILabel *inegralLabel;

/**
 *  积分信息(数据)
 */
@property (strong, nonatomic) IBOutlet UILabel *leftDrawerInegralContentLabel;

/**
 *  签名信息
 */
@property (strong, nonatomic) IBOutlet UILabel *signatureLabel;

@property (strong, nonatomic) UITableView *leftDrawerTableView;
/**
 *  footer视图
 */
@property (strong, nonatomic) UIView *leftDrawerFooterView;
/**
 *  系统设置
 */
@property (strong, nonatomic) UIButton *systemSettingButton;
/**
 *  版本信息
 */
@property (strong, nonatomic) UILabel *copyrightLabel;
/**
 *  创建一个用户详情对象
 */
@property (strong, nonatomic) UserDetailModel *userDetailObject;
/**
 *  数据请求方法
 */
- (void)_parsePersonalDataSource:(NSString *)urlString;


@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.signatureLabel.textColor = [UIColor colorWithRed:117/255.0 green:107/255.0 blue:163/255.0 alpha:1];
    [self.view addSubview:self.leftDrawerTableView];
    [self.view addSubview:self.leftDrawerFooterView];
    self.view.backgroundColor = [UIColor grayColor];
    self.typeHeaderImageArray = @[@"功能_健康日志",@"功能_我的任务",@"功能_我的家人",@"功能_我的好友",@"功能_我的医生",@"功能_我的关注",@"功能_邀请好友"];
    self.typeContentArray = @[@"健康日志",@"我的任务",@"我的家人",@"我的好友",@"我的医生",@"我的收藏",@"邀请好友"];
    [self setLeftDrawerView];
    [self setAnimation];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"PushAnimation" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        self.pushViewController = note.object;
    }];
    
    if (kScreenWidth == 320) {
        self.bigHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 150);
        self.leftDrawerTableView.frame = CGRectMake(0, 150, kScreenWidth, kScreenHeight - 150 - 55);
    }else if (kScreenWidth ==375){
        self.bigHeaderView.frame = CGRectMake(0, 26, kScreenWidth, 150);
        self.leftDrawerTableView.frame = CGRectMake(0, self.bigHeaderView.bottom, kScreenWidth, kScreenHeight - self.bigHeaderView.height - 55 - 26);
    }else{
        self.bigHeaderView.frame = CGRectMake(0, 26, kScreenWidth, 150);
        self.leftDrawerTableView.frame = CGRectMake(0, self.bigHeaderView.bottom, kScreenWidth, kScreenHeight - self.bigHeaderView.height - 55 - 26);
//        self.imageViewBaffle.frame = CGRectMake(15, 21, 90, 90);
//        self.leftDrawerHeaderImageView.frame = CGRectMake(15, 21, 90, 90);
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.leftDrawerNameLabel.text = self.userDetailObject.username;
    UIImage * userImage = [[UserManager shareInstance]getUserImage];
    
    [self.leftDrawerHeaderImageView setImage:userImage];
//    [self.leftDrawerHeaderImageView setImageWithURL:[NSURL URLWithString:self.userDetailObject.avatar] placeholderImage:[UIImage imageNamed:@"圆形头像"]];
    [self _parsePersonalDataSource:kBaseURL];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GightAnimation" object:nil];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置第一次开机动画 -
- (void)setAnimation{
    if (IPHONE_HEIGHT == kScreenHeight) {
        [UIView animateWithDuration:2 animations:^{
            [UIView animateWithDuration:1 animations:^{
                self.leftDrawerTableView.contentOffset = CGPointMake(0, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:1 animations:^{
                    self.leftDrawerTableView.contentOffset = CGPointMake(0, 0);
                }];
            }];
        }];
    }
}

#pragma mark - 设置话题数据信息自适应 -
- (void)setTopicAndInegralFrame{
    self.leftDrawerTopicContentLabel.frame = CGRectMake(116, 80, 21, 14);
    self.leftDrawerTopicContentLabel.font = [UIFont systemFontOfSize:12];
    if ([self.userDetailObject.threads isEqualToString:@"(null)"] || self.userDetailObject.threads == nil) {
        self.topicString = @"";
    }else{
        // 设置话题数据信息
        self.topicString = [NSString stringWithFormat:@"%@",self.userDetailObject.threads];
    }
    if ([self.userDetailObject.creadits isEqualToString:@"(null)"] || self.userDetailObject.threads == nil) {
        self.inegralString = @"";
    }else{
        // 设置话题数据信息
        self.inegralString = [NSString stringWithFormat:@"%@",self.userDetailObject.creadits];
    }
//    // 设置话题数据信息
//    self.topicString = [NSString stringWithFormat:@"%@",self.userDetailObject.threads];
//    self.inegralString = [NSString stringWithFormat:@"%@",self.userDetailObject.creadits];
    
    if (999 < [self.topicString intValue]) {
        self.topicString = [NSString stringWithFormat:@"1k+"];
    }
    if (999 < [self.inegralString intValue]) {
        self.inegralString = [NSString stringWithFormat:@"1k+"];
    }
    self.leftDrawerTopicContentLabel.text = self.topicString;
    self.leftDrawerTopicContentLabel.numberOfLines = 1;
    CGSize size = CGSizeMake(300, 14);
    //获取当前文本的属性
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12],NSFontAttributeName,nil];
    //获取文本需要的size
    CGSize redSize = [self.topicString boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    self.leftDrawerInegralContentLabel.text = self.inegralString;
    
//    if (kScreenWidth == 414) {
//        self.leftDrawerNameLabel.frame = CGRectMake(117, 48, 130, 20);
//        self.topLabel.frame = CGRectMake(120, 80, 24, 14);
//        self.leftDrawerTopicContentLabel.frame = CGRectMake(119 + 30, 80, redSize.width , 14);
//        self.verticalLine.frame = CGRectMake(119 + 30 + redSize.width + 10 , 81, 1 , 12);
//        self.inegralLabel.frame = CGRectMake(119 + 30 + redSize.width + 9 + 18, 80, 24, 14);
//        self.leftDrawerInegralContentLabel.frame = CGRectMake(119 + 30 + redSize.width +  9 + 18 + 24 + 4, 80, 21, 14);
//    }else{
        self.leftDrawerTopicContentLabel.frame = CGRectMake(119, 80, redSize.width , 14);
        self.verticalLine.frame = CGRectMake(119 + redSize.width + 10 , 81, 1 , 12);
        self.inegralLabel.frame = CGRectMake(119 + redSize.width + 9 + 18, 80, 24, 14);
        self.leftDrawerInegralContentLabel.frame = CGRectMake(119 + redSize.width +  9 + 18 + 24 + 4, 80, 21, 14);
//    }
    
}

#pragma mark - 显示数据 -
- (void)setInformationData{
    self.leftDrawerNameLabel.text = self.userDetailObject.username;
    BOOL isHaveUserImage = [[UserManager shareInstance]isHaveUserImage];
    if (isHaveUserImage == YES) {
        UIImage * userImage = [[UserManager shareInstance]getUserImage];
        [self.leftDrawerHeaderImageView setImage:userImage];
    }else{
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            UserModel * usermodel = [[UserManager shareInstance]getUserInfo];
            [self.leftDrawerHeaderImageView setImageWithURL:[NSURL URLWithString:usermodel.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];

        });
    }
    if (self.userDetailObject.bio.length == 0) {
        self.signatureLabel.text = @"暂无个性签名";
    }else{
        self.signatureLabel.text = self.userDetailObject.bio;
    }
}

#pragma mark - 设置头像并添加相关手势 -
- (void)setLeftDrawerView{
    /*
     *为左抽屉点击头像相关行视图添加手势
     */
    UITapGestureRecognizer *firstSurfaceTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTapHandleAction:)];
    firstSurfaceTap.numberOfTapsRequired = 1;
    [self.firstSurfaceView addGestureRecognizer:firstSurfaceTap];
    /*
     *为签名添加手势
     */
    UITapGestureRecognizer *secondSurfaceTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(signatureTapHandleAction:)];
    secondSurfaceTap.numberOfTapsRequired = 1;
    [self.secondSurfaceView addGestureRecognizer:secondSurfaceTap];
}


#pragma mark - tableView 的代理方法 -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *indentify = @"leftDrawerCell";
    LeftDrawerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentify];
    if (!cell) {
        if (kScreenWidth == 320) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"LeftDrawerTableViewCell" owner:self options:nil] firstObject];
        }else if (kScreenWidth == 375){
            cell = [[[NSBundle mainBundle] loadNibNamed:@"LeftDrawerTableViewCell" owner:self options:nil] objectAtIndex:1];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"LeftDrawerTableViewCell" owner:self options:nil] lastObject];}
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.typeHeaderImageView.image = [UIImage imageNamed:[self.typeHeaderImageArray objectAtIndex:indexPath.row]];
    cell.typeNameLabel.text = [self.typeContentArray objectAtIndex:indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 320) {
        return 44;
    }else if (kScreenWidth == 375){
        return 50;
    }else{
        return 60;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        MyHealthLogViewController *myHealthLogVC = [[MyHealthLogViewController alloc] init];
        myHealthLogVC.uidStr = self.userDetailObject.uid;
        [self.pushViewController.navigationController pushViewController:myHealthLogVC animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }
    if (indexPath.row == 2) {
        MyFamilyViewController * myFamily = [[MyFamilyViewController alloc] init];
        [self.pushViewController.navigationController pushViewController:myFamily animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }
    if (indexPath.row == 3) {
        MyFriendViewController * myFriendVC = [[MyFriendViewController alloc] init];
        [self.pushViewController.navigationController pushViewController:myFriendVC animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:nil];
    }
    if (indexPath.row == 4) {
        MyDoctorViewController *myDoctor = [[MyDoctorViewController alloc]init];
        [self.pushViewController.navigationController pushViewController:myDoctor animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }
    if (indexPath.row == 6){
        ShareViewController * shareViewController = [[ShareViewController alloc]initWithNibName:@"ShareViewController" bundle:nil];
        [self.pushViewController.navigationController pushViewController:shareViewController animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }else if (indexPath.row == 1){
        // “任务”
        TaskViewController *task = [[TaskViewController alloc] init];
        [self.pushViewController.navigationController pushViewController:task animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }
    if (indexPath.row == 5) {
        MyFocusViewcontroller * myFocusVC = [[MyFocusViewcontroller alloc] init];
        [self.pushViewController.navigationController pushViewController:myFocusVC animated:NO];
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];

    }
    
}


#pragma mark - 手势触发事件 -
- (void)headerTapHandleAction:(UIGestureRecognizer *)sender{
    /**
     *  跳转到个人信息界面
     */
    PersonalDataViewController *personalDataVC = [[PersonalDataViewController alloc] init];
    personalDataVC.userDetailObject = self.userDetailObject;
    [self.pushViewController.navigationController pushViewController:personalDataVC animated:NO];
    [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
    }];
}

- (void)signatureTapHandleAction:(UIGestureRecognizer *)sender{
    EditSignatureViewController *editsignatureVC = [[EditSignatureViewController alloc] init];
    editsignatureVC.returnWhichVC = YES;
    editsignatureVC.originalSignature = self.userDetailObject.bio;
    [self.pushViewController.navigationController pushViewController:editsignatureVC animated:NO];
    [self.drawerController closeDrawerAnimated:YES completion:nil];
}

#pragma mark - 网路数据请求 -
- (void)_parsePersonalDataSource:(NSString *)urlString{
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
        }else{
            NSDictionary * dataDic = [responseObject objectForKey:@"data"];
            [self.userDetailObject setValuesForKeysWithDictionary:dataDic];
            [UserId shareUid].uidStr = self.userDetailObject.uid;
        }
        [self setInformationData];
        [self setTopicAndInegralFrame];
       
    } failure:nil];
}
#pragma - mark 系统设置 -
- (void)systemSetting:(UIButton *)button
{
    SystemSetViewController * myFamily = [[SystemSetViewController alloc] init];
    [self.pushViewController.navigationController pushViewController:myFamily animated:NO];
    [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
    }];
    
}



#pragma mark - 懒加载 -
- (UITableView *)leftDrawerTableView{
    if (_leftDrawerTableView == nil) {
        _leftDrawerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 150, kScreenWidth, kScreenHeight - 150 - 55)];
        _leftDrawerTableView.backgroundColor = [UIColor clearColor];
        _leftDrawerTableView.dataSource = self;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 8)];
        view.backgroundColor=[UIColor clearColor];
        _leftDrawerTableView.tableHeaderView = view;
        _leftDrawerTableView.delegate = self;
        _leftDrawerTableView.separatorStyle = NO;
        _leftDrawerTableView.showsVerticalScrollIndicator = NO;
    }
    return _leftDrawerTableView;
}

- (UIView *)leftDrawerFooterView{
    if (_leftDrawerFooterView == nil) {
        _leftDrawerFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 55, kScreenWidth, 55)];
        self.systemSettingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.systemSettingButton.frame = CGRectMake(20, 15, 100, 20);
        self.systemSettingButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20);
        [self.systemSettingButton setTitle:@"系统设置" forState:UIControlStateNormal];
        self.systemSettingButton.titleLabel.font= [UIFont systemFontOfSize:LABEL_FONT_SIZE_TIME + 2];
        [self.systemSettingButton setTitleColor:[UIColor lightGrayColor]forState:UIControlStateNormal];
        [self.systemSettingButton setImage:[UIImage imageNamed:@"功能_系统设置"] forState:UIControlStateNormal];
        [self.systemSettingButton addTarget:self action:@selector(systemSetting:) forControlEvents:UIControlEventTouchUpInside];
        [_leftDrawerFooterView addSubview:self.systemSettingButton];
        self.copyrightLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 180, 15, 160, 20)];
        self.copyrightLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TIME];
        self.copyrightLabel.textAlignment = NSTextAlignmentCenter;
        self.copyrightLabel.textColor = [UIColor lightGrayColor];
        self.copyrightLabel.text = @"安好 版权所有 2014";
        [_leftDrawerFooterView addSubview:self.copyrightLabel];
    }
    return _leftDrawerFooterView;
}

- (UserDetailModel *)userDetailObject{
    if (_userDetailObject == nil) {
        _userDetailObject = [[UserDetailModel alloc] init];
    }
    return _userDetailObject;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
